#include "HttpReqeustTask.h"
#include "ConnectionPool.h"


HttpRequestTask::HttpRequestTask(qintptr descriptor)
    : socketDescriptor(descriptor) {
    setAutoDelete(true);
}

void HttpRequestTask::run()
{
    //QThread *current = QThread::currentThread();
    //socket->moveToThread(current); // 关键步骤
    //if (socket->waitForReadyRead(5000)) {
        //processRequest();
    //}

    //socketDescriptor.moveToThread(QThread::currentThread());

    socket = new QTcpSocket();
    socket->setSocketDescriptor(socketDescriptor);

    if(socket->waitForReadyRead(500)) {  // 等待数据到达:ml-citation{ref="5,8" data="citationList"}
         processRequest();
    }



    safeCloseSocket();
}

void HttpRequestTask::processRequest()
{
    QByteArray requestData = socket->readAll();
    if (requestData.startsWith("POST"))
    {
        // 提取POST正文（假设简单文本格式）
        int headerEnd = requestData.indexOf("\r\n\r\n");
        QByteArray postData = requestData.mid(headerEnd + 4);

        // 处理JSON格式数据
        if (requestData.indexOf("application/json") != -1)
        {
            if(requestData.indexOf("/login") != -1)
            {
                qDebug() << "调用login接口" ;
                //login回复
                LoginReplay(postData);
                return;
            }
            else if(requestData.indexOf("/getpersoninfolist") != -1)
            {
                qDebug() << "调用getpersoninfolist接口" ;
                //getpersoninfolist
                GetPersonInfoListReplay(postData);
                return;
            }
            else
            {
                ReplayFailNotFound();
            }

        }
    }
}


void HttpRequestTask::safeCloseSocket() {
    socket->disconnectFromHost();
    if (socket->state() != QAbstractSocket::UnconnectedState) {
        socket->waitForDisconnected(1000);
    }
    socket->deleteLater(); // 线程安全释放
}

void HttpRequestTask::LoginReplay(const QByteArray & postData)
{
    QJsonDocument doc = QJsonDocument::fromJson(postData);
    if (!doc.isNull())
    {
        qDebug() << "Received JSON:" << doc.toJson();
    }

    QJsonObject rootObj = doc.object();
    if(!rootObj.contains("username") ||
        !rootObj.contains("password"))
    {
        qDebug() << "错误：缺少必要字段" << doc.toJson();
        return;
    }

    QJsonValue nameValue = rootObj.value("username");
    QJsonValue passValue = rootObj.value("password");
    if(!nameValue.isString() || !passValue.isString())
    {
        //返回参数错误, 进行回复
        qDebug() << "错误：字段类型应为字符串" << doc.toJson();
        return;
    }

    QString username = nameValue.toString();
    QString password = passValue.toString();

    //连接数据库
    QSqlDatabase db = ConnectionPool::instance().getConnection();
    QSqlQuery query(db);

    //从数据库取出比较
    query.prepare("SELECT password FROM users WHERE username = :user");
    query.bindValue(":user", username);

    if (query.exec() && query.next())
    {
        QString dbpassword = query.value(0).toString();
        if (dbpassword == password)
        {
            qDebug() << dbpassword;

            // 构造JSON响应
            QJsonObject jsonObj;
            jsonObj["code"] = 200;
            jsonObj["message"] = "Login success";

            // 转换为JSON字符串
            ReplaySuccess(jsonObj);
        }
    }
    else
    {
        qDebug() << "查询失败：" << query.lastError();
    }

    ConnectionPool::instance().releaseConnection(db);
}

void HttpRequestTask::ReplaySuccess(const QJsonObject & jsResult)
{
    QJsonDocument doc(jsResult);
    QByteArray jsonData = doc.toJson();

    // 构造完整HTTP响应
    QByteArray response = "HTTP/1.1 200 OK\r\n";
    response += "Content-Type: application/json\r\n";
    response += "Content-Length: " + QByteArray::number(jsonData.size()) + "\r\n";
    response += "Connection: close\r\n\r\n";
    response += jsonData;

    // 发送响应
    socket->write(response);
    socket->flush();
}

void HttpRequestTask::ReplayFailNotFound()
{
    QJsonObject jsonObj;
    jsonObj["code"] = 400;
    jsonObj["message"] = "Not Found";

    QJsonDocument doc(jsonObj);
    QByteArray jsonData = doc.toJson();

    // 构造完整HTTP响应
    QByteArray response = "HTTP/1.1 400 Not Found\r\n";
    response += "Content-Type: application/json\r\n";
    response += "Content-Length: " + QByteArray::number(jsonData.size()) + "\r\n";
    response += "Connection: close\r\n\r\n";
    response += jsonData;

    // 发送响应
    socket->write(response);
    socket->flush();
}

void HttpRequestTask::GetPersonInfoListReplay(const QByteArray & postData)
{
    QJsonDocument doc = QJsonDocument::fromJson(postData);
    if (!doc.isNull())
    {
        qDebug() << "Received JSON:" << doc.toJson();
    }

    QJsonObject rootObj = doc.object();
    if(!rootObj.contains("limit") ||
        !rootObj.contains("page"))
    {
        qDebug() << "错误：缺少必要字段" << doc.toJson();
        return;
    }

    QString strname;
    if(rootObj.contains("name"))
    {
        QJsonValue nameValue = rootObj.value("name");
        if(nameValue.isString())
        {
            strname = nameValue.toString();
        }
    }


    QJsonValue limitValue = rootObj.value("limit");
    QJsonValue pageValue = rootObj.value("page");
    if(!isJsonInt(limitValue) || !isJsonInt(pageValue))
    {
        //返回参数错误, 进行回复
        qDebug() << "错误：字段类型有错误" << doc.toJson();
        return;
    }

    int nlimit = limitValue.toInt();
    int npage = pageValue.toInt();

    //连接数据库
    QSqlDatabase db = ConnectionPool::instance().getConnection();
    QSqlQuery query(db);

    //从数据库取出比较
   // query.prepare("SELECT password FROM users WHERE username = :user");
    //query.bindValue(":user", username);

    QString sql;
    if(strname.isEmpty())
    {

        sql = QString("SELECT * FROM personinfo ORDER BY id LIMIT %1 OFFSET %2")
        .arg(nlimit)
        .arg((npage-1)*nlimit);
    }
    else
    {
        sql = QString("SELECT * FROM personinfo WHERE name LIKE '%%1%' ORDER BY id LIMIT %2 OFFSET %3")
        .arg(strname)  // 要搜索的名称关键字
        .arg(nlimit)
        .arg((npage-1)*nlimit);
    }



    if(!query.exec(sql))
    {
        qDebug() << "Query failed:" << query.lastError();
        return;
    }

    QJsonArray jslist;
    while(query.next())
    {
        // 处理每行数据
        QJsonObject jstemp;
        jstemp["name"] = query.value("name").toString();

        jslist.append(jstemp);

    }


    QSqlQuery countQuery(db);
    QString countsql;
    if(strname.isEmpty())
    {
        countsql = QString("SELECT COUNT(*) FROM personinfo");
    }
    else
    {
        countsql = QString("SELECT COUNT(*) FROM personinfo WHERE name LIKE '%%1%'").arg(strname);
    }


    if(!countQuery.exec(countsql) || !countQuery.next())
    {
        qDebug() << "countQuery failed:" << query.lastError();
        return;
    }
    int ntotalcount = countQuery.value(0).toInt(); //总数
    int ntotalpage = (ntotalcount + nlimit - 1) / nlimit; //总页数


    QJsonObject jsresult;
    jsresult["total"] = ntotalcount;
    jsresult["totalpage"] = ntotalpage;
    jsresult["page"] = npage;
    jsresult["limit"] = nlimit;
    jsresult["list"] = jslist;

    QJsonObject jsonObj;

    jsonObj["code"] = 200;
    jsonObj["message"] = "success";
    jsonObj["result"] = jsresult;

    // 转换为JSON字符串
    ReplaySuccess(jsonObj);

    ConnectionPool::instance().releaseConnection(db);
}

bool HttpRequestTask::isJsonInt(const QJsonValue &value) {
    if(value.isDouble()) {
        double d = value.toDouble();
        return d == floor(d) && d >= INT_MIN && d <= INT_MAX;
    }
    return false;
}
